<?php
namespace app\index\controller;

use app\common\model\Gameulog;
use app\common\model\Player;
use think\cache\driver\Redis;
use think\Controller;
use think\Db;
use app\common\controller\IndexBase;
use think\facade\Log;
use think\facade\Session;
use think\Loader;
use think\facade\App;

/**
 * 后台首页
 * Class Index
 * @package app\admin\controller
 */
class Game extends IndexBase
{
    protected function initialize()
    {
        parent::initialize();
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        $redis = new Redis();
        $game = $this->game;
        if($this->token){
            $player = $redis->get($this->token);

            if(!empty($player)){
                $token = $player['token'];
                if (strpos($game['api_login_url'], '?') !== false) {
                    $game['api_login_url'] = $game['api_login_url']."&token=".$token;
                } else {
                    $game['api_login_url'] = $game['api_login_url']."?token=".$token;
                }
            }
        }else{
            $game['api_login_url'] = "";
        }
        $this->assign('game', $game);
        return $this->fetch();
    }

    /**
     * 注册
     */
    private function register($params){
        $player = Player::getOne(['account'=>"g_".$params['uid']]);
        if(!$player){
            //注册
            $data['account'] = "g_".$params['uid'];
            $data['password'] = get_encrypt('123456');
            $data['type'] = 0;
            $data['cid'] = $this->cid;
            $data['gid'] = $this->gid;
            try {
                Db::startTrans();
                $player = Player::register($data);
                Db::commit();
            }catch (Exception $e) {
                Db::rollback();
                Log::info("用户注册失败:".$e->getMessage());
            }
            $data['uid'] = $player['id'];
            //记录登录信息
            Gameulog::addLog($data);
            $token = get_encrypt($data['uid']);
            $player['token'] = $token;
            unset($player['password']);
            Session::set('palyerinfo', json_encode($player));
            //redis 保存用户信息
            $redis = new Redis();
            $redis->set($token, $player);
        }
    }

    private function check_sign($params,$key)
    {
        unset($params[1]);
        $sign = $params['sign'];
        unset($params['sign']);
        unset($params['rp_token']);
        $check_sign = get_sign($params,$key);
        if($check_sign != $sign){
            return false;
        }
        return true;
    }

}